import { EventMessage } from "../../common/config/EventMessageConfig";
import { LayerID } from "../../common/config/GameUIConfig";
import { net } from "../../common/net/HttpRequest";
import { GameManager } from "../game/GameManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Game extends cc.Component {

    @property(cc.Node)
    chessBoard: cc.Node = null;

    @property(cc.Node)
    toast: cc.Node = null;

    @property(cc.Node)
    gameOver: cc.Node = null;

    @property(cc.SpriteFrame)
    chessSpriteList: cc.SpriteFrame[] = [];

    @property(cc.Label)
    numLabel: cc.Label = null;

    @property(cc.Label)
    timeLabel: cc.Label = null;

    chessMap: Map<number, number> = new Map<number, number>();

    beforeChessItem = -1;

    chessList = [];
    itemNum = 12;
    isInAni = false;

    schu = null;

    start() {
        this.refreshGame();
        GameManager.getInstance().message.on(EventMessage.GAME_REFRESHUI, this.refreshGame, this);
    }

    refreshGame() {
        this.chessBoard.active = false;
        this.gameOver.active = false;
        GameManager.getInstance().gameData.gameOverType = -1;
        net.httpPost("https://dati.api.anhuiyun.com/api/acitvity/game/start", { q: "3vAtHpVM3E7YtjZQlBCk", app: "dt" }
        ).then((data: any) => {
            data = JSON.parse(data);
            console.log(data)
            if (data.code == 400) {
                GameManager.getInstance().gameData.gameMessage = data.message;
                GameManager.getInstance().message.dispatchEvent(EventMessage.GAME_MESSAGE);
                GameManager.getInstance().ui.removeView(LayerID.game);
                return;
            } else if (data.code == 200) {
                GameManager.getInstance().gameData.gameId = data.data.id;
                this.numLabel.string = "" + GameManager.getInstance().gameData.gameNum;
                GameManager.getInstance().gameData.gameNum -= 1;
                this.chessBoard.active = true;
            } else if (data.code == 401) {
                if (!GameManager.getInstance().gameData.isDug) {
                    let targetUrl = '/dati/3vAtHpVM3E7YtjZQlBCk';
                    window.location.href = targetUrl;
                    return;
                }
            }
        });

        this.unschedule(this.schu);
        let time = 50;
        this.timeLabel.string = time + "";
        this.schu = () => {
            time -= 1;
            this.timeLabel.string = time + "";
            if (time <= 0) {
                this.unschedule(this.schu);
                // GameManager.getInstance().ui.openView(LayerID.gameReward);
                net.httpPost("https://dati.api.anhuiyun.com/api/acitvity/game/store",
                    { q: "3vAtHpVM3E7YtjZQlBCk", app: "dt", id: GameManager.getInstance().gameData.gameId, is_over: 0 })
                this.gameOver.active = true;
            }
        }
        this.schedule(this.schu, 1)
        this.chessList = [];
        for (let i = 0; i < this.itemNum; i++) {
            this.chessBoard.children[i].getComponent(cc.Sprite).spriteFrame = this.chessSpriteList[0];
            this.chessBoard.children[i].active = true;
            this.chessList.push(i);
        }
        // this.chessList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19];
        for (let i = 0; i < this.itemNum / 2; i++) {
            let num = this.getRandom(1, 10);

            let indexNum = this.getRandom(0, this.chessList.length - 1);
            let index1 = this.chessList[indexNum];
            this.chessList.splice(indexNum, 1);

            let indexNum2 = this.getRandom(0, this.chessList.length - 1);
            let index2 = this.chessList[indexNum2];
            this.chessList.splice(indexNum2, 1);

            this.chessMap.set(index1, num);
            this.chessMap.set(index2, num);
        }
    }

    // -5 5     5 10
    getRandom(min, max) {
        //@ts-ignore
        return cc.math.randomRangeInt(min, max);

        return Math.floor(Math.random() * (max - min)) + min;
    }

    checkList() {
        let isOver = true;
        for (let i = 0; i < this.itemNum; i++) {
            if (this.chessMap.get(i) != -1) {
                isOver = false;
                return;
            }
        }
        this.unschedule(this.schu);
        net.httpPost("https://dati.api.anhuiyun.com/api/acitvity/game/store", { q: "3vAtHpVM3E7YtjZQlBCk", app: "dt", id: GameManager.getInstance().gameData.gameId, is_over: 1 }
        ).then((data: any) => {
            data = JSON.parse(data);
            console.log(data)
            if (data.code == 400) {
                GameManager.getInstance().gameData.gameMessage = data.message;
                GameManager.getInstance().message.dispatchEvent(EventMessage.GAME_MESSAGE);
                GameManager.getInstance().ui.removeView(LayerID.game);
            } else if (data.code == 200) {
                console.log(data.data)
                console.log(data.data.redbag)
                console.log(data.data.redbag.index)
                GameManager.getInstance().gameData.gameOverType = data.data.redbag.index;
                GameManager.getInstance().ui.openView(LayerID.gameTurntable);
            }
        });
    }

    clickItem(eve) {
        if (this.isInAni) {
            return;
        }
        let name = parseInt(eve.target.name);
        if (this.beforeChessItem == name) {
            return;
        }
        this.isInAni = true;
        let nowIndex = this.chessMap.get(name);
        console.log(name, this.chessMap)

        cc.tween(eve.target)
            .to(0.25, { scaleX: 0 })
            .call(() => {
                eve.target.getComponent(cc.Sprite).spriteFrame = this.chessSpriteList[nowIndex];
                cc.tween(eve.target)
                    .to(0.25, { scaleX: 1.3 })
                    .call(() => {
                        if (this.beforeChessItem == -1) {
                            this.beforeChessItem = name;
                            this.isInAni = false;
                        } else {
                            let beforeIndex = this.chessMap.get(this.beforeChessItem);
                            if (beforeIndex == nowIndex) {
                                this.chessBoard.children[this.beforeChessItem].active = false;
                                eve.target.active = false;
                                this.isInAni = false;
                                this.chessMap.set(name, -1);
                                this.chessMap.set(this.beforeChessItem, -1);
                                this.checkList();
                            } else {
                                let node1 = eve.target
                                cc.tween(node1)
                                    .delay(0.1)
                                    .to(0.25, { scaleX: 0 })
                                    .call(() => {
                                        node1.getComponent(cc.Sprite).spriteFrame = this.chessSpriteList[0];
                                        cc.tween(node1)
                                            .to(0.25, { scaleX: 1.3 })
                                            .start()
                                    })
                                    .start()
                                let node2 = this.chessBoard.children[this.beforeChessItem];
                                cc.tween(node2)
                                    .delay(0.1)
                                    .to(0.25, { scaleX: 0 })
                                    .call(() => {
                                        node2.getComponent(cc.Sprite).spriteFrame = this.chessSpriteList[0];
                                        cc.tween(node2)
                                            .to(0.25, { scaleX: 1.3 })
                                            .call(() => {
                                                this.isInAni = false;
                                            })
                                            .start()
                                    })
                                    .start()
                            }
                            this.beforeChessItem = -1;
                        }
                    })
                    .start()
            })
            .start()
    }

    clickGameTurntable() {
        GameManager.getInstance().ui.openView(LayerID.gameTurntable);
    }

    toastSchu = null;
    showToast(str) {
        this.toast.active = true;
        this.toast.getComponent(cc.Label).string = str;
        this.unschedule(this.toastSchu);
        this.toastSchu = () => {
            this.toast.active = false;
        }
        this.scheduleOnce(this.toastSchu, 3)
    }

    // update (dt) {}
}
